<template>
<div class="contain">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header-box :title="'出差申请'" :hasArrow="true"></header-box>
  <detail-user></detail-user>
  <progress-box :formData="true" @showLoadProgress="showLoadProgress"></progress-box>
  <div class="form-control displayflex">
    <div class="label require">开始时间</div>
    <div class="ctx-wrap flex1">
      <datetime v-model="startTime" 
          format="YYYY-MM-DD HH:mm:00"
          year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{startTime}}</datetime>
      <div v-if="!startTime" class="remind">请选择</div>
    </div>
    <i class="iconfont icon-arrow"></i>
  </div>
  <div class="form-control displayflex">
    <div class="label require">结束时间</div>
    <div class="ctx-wrap flex1">
      <datetime v-model="endTime" 
          format="YYYY-MM-DD HH:mm:00"
          year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{endTime}}</datetime>
      <div v-if="!endTime" class="remind">请选择</div>
    </div>
    <i class="iconfont icon-arrow"></i>
  </div>
   <div class="form-control displayflex">
    <popup-picker class="picker-wrap require" 
        title="请假类型" 
        :data="triptypeList" 
        placeholder="请选择" 
        value-text-align="right"
        :show-name="true"
        v-model="triptype"></popup-picker>
    <i class="iconfont icon-arrow"></i>
  </div>
   <div class="form-control displayflex">
    <div class="label require">请假时长</div>
    <div class="ipt-wrap flex1"><input type="number" placeholder="" v-model="leavedays"/></div>
    <div class="unit">天</div>
  </div>
  <div class="form-control displayflex">
    <div class="label require" :class="{'require':(transportation!='1')}">请假事由</div>
    <div class="text-wrap flex1">
      <textarea rows="3" placeholder="请填写请假事由" v-model="reasons"></textarea>
    </div>
  </div>
  <uploader-img :attaches="attaches" @getImgArr="getImgArr" ref="uploader"></uploader-img>
  
  <div class="btn-group displayflex">
    <div class="flex1 save" @click="changeImg(1)">保 存</div>
    <div class="flex1 submit" v-if="btnGroup.wfsubmit || !guid" @click="changeImg(2)">提 交</div>
    <div class="dele" v-if="guid" @click="deleForm"><i class="iconfont icon-delbtn"></i></div>
  </div>
</div>
</template>
<script>
import progressBox from "@/components/share/progress.vue";
import detailUser from "@/components/share/detailUser.vue";
import uploaderImg from "@/components/share/uploaderImg.vue";
import axios from "axios";

export default {
  components:{
    detailUser,
    uploaderImg,
    progressBox
  },
  data() {
    return {
      startTime:'',
      endTime:'',
      //请假类型
      triptype: [],
      triptypeList: [],
      //时长
      leavedays:'',
      reasons:'',
      projectname:'',
      destination:'',
      planinfo:'',
      transportationList:'',
      transportation:'1',
      showLoad:false,
      showLoadT:false,
      showLoadP:false,
      btnGroup:'',
      attaches:[],
      fileattaches:[],
      attachesBase:[],
      savedGuid:'',
    };
  },
  computed: {
    userInfo(){
      return localStorage.UserInfo?JSON.parse(localStorage.UserInfo):'';
    },
    guid(){
      return this.$route.query.guid || '';
    },
    bizdataguid(){
      return this.$route.query.bizdataguid || "";
    },
  },
  watch:{
    showLoadT(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
    showLoadP(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
  },
  created() {
      this.getleaveType();
    if(this.guid){
      this.getBtn();
      this.getData();
    }
  },
  mounted(){
    this.$nextTick(() => {
      
    });
  },
  methods: {
    
    //获取上传的图片
    getImgArr(val){
      this.attachesBase = val;
    },

    //转换图片
    changeImg(step){
      const uploadApi = process.env.API_ROOT + '/app/openroute/CSBR.Management.AppService.Service.V1.DataService/FilesUpload';
      this.showLoadT = true;
      var attachesBase = this.attachesBase;
      var data = [];
      var _this = this;

      if(attachesBase.length == 0){
        this.save(step);
        return false;
      }
      for(let i in attachesBase){
        //接口调整图片前缀
        // let pic = attachesBase[i].indexOf('base64,') > -1?attachesBase[i].split('base64,')[1]:attachesBase[i];
        let pic = attachesBase[i].replace(/\n/g, '');

        let timestamp = new Date().getTime(),
            item = {
              "base64code" : pic,
            };
        data.push(item);
      };

      //new batch upload
      let reqList = [],
          resList = [],
          picNewArr = [],
          hasError = false;
      for(let i = 0; i < data.length; i++)
      {
        let item = [data[i]];
        let req = axios.post(uploadApi,item)
        reqList.push(req);
      }

      axios.all(reqList)
        .then(axios.spread(function(...resList) {
          resList.forEach((item) => {
            if(item.data.code == 'SUCC')
            {
              let url = JSON.parse(item.data.data)[0],
                  filename = url.split('/')[2],
                  result = {
                    type : null,
                    url : url,
                    fileid: null,
                    filename: filename
                  };
              picNewArr.push(result);
            }
            else
            {
              hasError = true;
            }
          });
          
          _this.attachesBase = [];
          _this.$refs.uploader.resetImgListBase();

          if(_this.attaches){
            _this.attaches = _this.attaches.concat(picNewArr);
          } else {
            _this.attaches = picNewArr;
          };

          if(hasError) {
            _this.showLoadT = false;
            _this.$vux.toast.show({
              type: "warn", //success, warn, cancel, text
              text: "部分图片上传发生错误，请重试"
            });
          } else {
            // console.log(_this.attaches);
            _this.save(step);
          }
        })
      );
      
    },
    //请假类型
    getleaveType(){
      var self =this;
            var data={};
             this.Ajax.post('LeaveApplyService/MyLeaveApplyInit',data).then(function(resp) {
                if(resp.code == 'SUCC'){
                  var res = resp.data;
                  var typejson =[];
                   JSON.parse(res).leavetype.forEach(element => {
                      var item ={
                         'value':element.value,
                         'name':element.caption
                      };
                      typejson.push(item);
                   });
                }
                 self.triptypeList.push(typejson);
             });
    },
    //获取详情页
    getData(){
      var data = {
            "guid": this.bizdataguid || this.guid
          };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('LeaveApplyService/GetLeaveApplyById',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          var detailCtx = JSON.parse(resp.data);
           console.log(detailCtx,"$$")
          //_this.trippartner = detailCtx.trippartner;
          _this.startTime= detailCtx.begindate.replace("T"," ");
          _this.endTime = detailCtx.enddate.replace("T"," ");
          _this.leavedays = detailCtx.leavedays;
          _this.triptype.push(detailCtx.leavetype);
          _this.reasons = detailCtx.reasons;
        
          // _this.attaches = (detailCtx.attaches && detailCtx.attaches != '')?JSON.parse(detailCtx.attaches):[];
          if(detailCtx.attaches && detailCtx.attaches != ''){
            var attachesArr = JSON.parse(detailCtx.attaches);
            var formatArr = ['gif','jpeg','jpg','png'];
            var picArr = [];
            for(let i in attachesArr){
              var url = attachesArr[i].url
              var format = url.split('.')[1];
              if(formatArr.indexOf(format)>-1){
                _this.attaches.push(attachesArr[i])
              }else{
                _this.fileattaches.push(attachesArr[i]);
              }
            }
          }
        }else{
       
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
        _this.showLoadT = false;
      });
    },
    //表单验证
    checkForm(){
      if(!this.startTime){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "开始时间不能为空"
        });
        return false;
      };
      if(!this.endTime){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "结束时间不能为空"
        });
        return false;
      };
      if(this.startTime>this.endTime){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "开始时间不能大于结束时间"
        });
        return false;
      };
      console.log(this.triptype);
      if(this.triptype.length ==0){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择请假类型"
        });
        return false;
      };
      if(!this.leavedays){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请假时长不能为空"
          });
          return false;
        };
      if(!this.reasons){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请假事由不能为空"
        });
        return false;
      };
      return true;
    },

    //保存
    save(step){
      if(!this.checkForm()){
        this.showLoadT = false;
        return false;
      };
      // this.changeImg();
      // this.showLoadT = true;
      var _this = this;
      //attaches定义附件合并，需要包含this.attaches和this.fileattaches;
      let mixedAttaches = [];
      if(this.attaches.length > 0)
      {
        mixedAttaches = mixedAttaches.concat(this.attaches);
      }
      if(this.fileattaches.length > 0)
      {
        mixedAttaches = mixedAttaches.concat(this.fileattaches)
      }
      let Now = new Date(),
          nowStr = `${Now.getFullYear()}-${Now.getMonth() + 1}-${Now.getDate()} ${Now.getHours()}:${Now.getMinutes()}:${Now.getSeconds()}`;
      var data = {
          "guid": this.guid,     // 空则为新增，非空则为编辑
          "applicant": this.userInfo.name,
          "staffid": this.userInfo.staffid,
          "deptguid": this.userInfo.deptguid,
          "deptname": this.userInfo.deptname,
          "LeaveDays":this.leavedays,
          "applydate": nowStr,
          "begindate": this.startTime,
          "enddate": this.endTime,
          "Reasons": this.reasons,
          "LeaveType": this.triptype[0],
          "Attaches": mixedAttaches.length > 0 ? JSON.stringify(mixedAttaches):'',
      };
      //防止重复的判断
      if(this.savedGuid != '')
      {
        data.guid = this.savedGuid;
      }
      
      this.Ajax.post('LeaveApplyService/MyLeaveApplySave',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          var guid = (JSON.parse(resp.data)).guid;
          _this.savedGuid = guid;
          if(step=="2"){
            _this.submit(guid);
          } else {
            _this.$vux.toast.show({
              type: "success", //success, warn, cancel, text
              text: resp.message
            });
            _this.showLoadT = false;
          }
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
          _this.showLoadT = false;
        };
      });
    },
    
    //提交
    submit(id){
      var data = { 
          "bizguid": id,///保存生成的guid,,,,
          "pagekey": "MyLeaveApply",             // 可用场景 MyBizTripApply    BizTripAudit
          "staffid": this.userInfo.staffid,
          "todoguid": "",
          "result": "Y",
          "rejectreason": ""
      };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('LeaveApplyService/Submit',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          _this.$vux.toast.show({
            type: "success", //success, warn, cancel, text
            text: "提交成功",
            onHide () {
              _this.$router.go(-1);
            }
          });
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        };
        _this.showLoadT = false;
      });
    },

    //判断按钮权限（提交 撤回 审核）
    getBtn(){
      var data = {
                "bizguid": this.guid,
                "pagekey": "MyLeaveApply",// 可用场景 MyBizTripApply    BizTripAudit
                "staffid": this.userInfo.staffid,
                "todoguid": ""
            };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('LeaveApplyService/WFAvailableButtons',data).then(function(resp) {
        if(resp.code == 'SUCC'){
           console.log(JSON.parse(resp.data),"%%0000000")
          _this.btnGroup = resp.data?JSON.parse(resp.data):'';
        }else{
            console.log(resp.message +"123213");
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
        _this.showLoadT = false;
      });
    },

    //删除表单
    deleForm(){
      var data = {
                "guid": this.guid
            };
      var _this = this;
      this.$vux.confirm.show({
        title:'提示',
        content: '确认删除申请吗？',
        onConfirm () {
          _this.showLoadT = true;
          _this.Ajax.post('LeaveApplyService/MyLeaveApplyDelete',data).then(function(resp) {
            if(resp.code == 'SUCC'){
              _this.$vux.toast.show({
                type: "success", //success, warn, cancel, text
                text: resp.message,
                onHide () {
                  _this.$router.go(-1);
                }
              });
            }else{
              _this.$vux.toast.show({
                type: "warn", //success, warn, cancel, text
                text: resp.message
              });
            }
            _this.showLoadT = false;
          });
        }
      });
    },

    showLoadProgress(val){
      this.showLoadP = val;
    }
  }
};
</script>